var dmNetwork = require('../../../utils/network.js')
var util = require('../../../utils/util.js')
var team_id;
var project_id;
var extra_info;
// scheduling.js
Page({

  /**
   * 页面的初始数据
   */
  data: {

    isShowTag:false,
    hasEmptyGrid: false,
    attendanceList: [

    ],

    monthAttendanceStatu: {},
  },
  getDayAttdance(e) {
    //console.log(e.currentTarget.dataset.idx+1)
    var index = e.currentTarget.dataset.idx
    const get_year = this.data.cur_year;
    const get_month = this.data.cur_month;
    const get_day = index + 1;

    this.setData({
      cur_date: get_day
    });

    var task_id = this.data.monthAttendanceStatu.status[index].task_id;
    var task_status = this.data.monthAttendanceStatu.status[index].status;

    if (0 == task_status) {
      if (1 == this.data.monthAttendanceStatu.status[index].has_schedule) {

        this.getDaySchedule(get_year + "-" + get_month + "-" + get_day, task_id)
      } else {
        this.setData({
          attendanceList: [

          ]
        })
      }
    } else {
      this.getDayStatus(get_year + "-" + get_month + "-" + get_day, task_id)
    }


  },
  imgYu: function (event) {
    var src = event.currentTarget.dataset.src;//获取data-src
    var imgList = event.currentTarget.dataset.list;//获取data-list

    //图片预览
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgList // 需要预览的图片http链接列表
    })
  },
  getSystemInfo() {
    try {
      const res = wx.getSystemInfoSync();
      this.setData({
        bottomHeight: res.windowHeight - 420
      });
    } catch (e) {
      console.log(e);
    }
  },
  getThisMonthDays(year, month) {
    return new Date(year, month, 0).getDate();   //返回一个月总天数 

  }, getFirstDayOfWeek(year, month) {
    return new Date(Date.UTC(year, month - 1, 1)).getDay(); //返回1号是星期几
  },
  calculateEmptyGrids(year, month) {
    const firstDayOfWeek = this.getFirstDayOfWeek(year, month); //返回1号是星期几
    const lastMonthDays = this.getThisMonthDays(year, month - 1);
    let empytGrids = [];
    if (firstDayOfWeek > 0) {
      for (let i = 0; i < firstDayOfWeek; i++) {
        empytGrids.push(lastMonthDays - firstDayOfWeek + i + 1);   //前面加空天数
      }

      this.setData({
        hasEmptyGrid: true,
        empytGrids
      });
    } else {
      this.setData({
        hasEmptyGrid: false,
        empytGrids: []
      });
    }
  },
  calculateDays(year, month) {
    let days = [];

    const thisMonthDays = this.getThisMonthDays(year, month); //返回一个月总天数 

    for (let i = 1; i <= thisMonthDays; i++) {
      days.push(i);
    }
    const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
    const len = days.length + firstDayOfWeek;
    let endEmpty = [];
    for (let i = len; i < 42; i++) {
      endEmpty.push(i + 1 - len);
    }
    this.setData({
      days,
      endEmpty
    });

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const date = new Date();
    const cur_year = date.getFullYear();
    const cur_month = date.getMonth() + 1;
    const cur_date = date.getDate();
    const weeks_ch = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    this.calculateEmptyGrids(cur_year, cur_month);
    this.calculateDays(cur_year, cur_month);
    this.getSystemInfo();
    this.setData({
      cur_year,  //年
      cur_month, //月
      cur_date,  //天
      weeks_ch   //星期
    })

    project_id = options.project_id
    team_id = options.team_id;
    this.getMonthStatus(cur_year + '-' + cur_month)
  },
  getMonthStatus: function (date) {
    var rDate = {
      team_id: team_id,
      project_id: project_id,
      month: date
    }
    dmNetwork.get(dmNetwork.attdanceMonthStatus, rDate, (res) => {

      this.setData({
        isShowTag:true,
        monthAttendanceStatu: res.data.data
      })
      var index = this.data.cur_date - 1
      var task_id = res.data.data.status[index].task_id;
      var task_status = res.data.data.status[index].status;

      if (0 == task_status) {
        // this.setData({
        //   attendanceList: [

        //   ]
        // })

        if (1 == this.data.monthAttendanceStatu.status[index].has_schedule) {

          this.getDaySchedule(this.data.cur_year + "-" + this.data.cur_month + "-" + this.data.cur_date, task_id)
        } else {
          this.setData({
            attendanceList: [

            ]
          })
        }
      } else {
        this.getDayStatus(this.data.cur_year + "-" + this.data.cur_month + "-" + this.data.cur_date, task_id)
      }

    }, (error) => {

    })
  },
  getDaySchedule: function (date, task_id) {
    var rDate = {
      team_id: team_id,
      project_id: project_id,
      date: date,
    }
    dmNetwork.get(dmNetwork.user_date_schedule, rDate,
      (res) => {
        console.log(res.data)
        if (res.data.length == 0) {
          this.setData({
            attendanceList: [

            ]
          })
          return
        }
        var resultList = []

        for (var i = 0; i < res.data.data.length; i++) {
          var resultData = {}
          resultData.hasAction = false
          resultData.hasReason = true
          resultData.require_time = res.data.data[i].time
          resultData.name = res.data.data[i].name
          resultData.schedule_id = res.data.data[i].schedule_id
          resultData.position_id = res.data.data[i].position_id
          resultData.cross = res.data.data[i].cross

          if (i % 2 == 0) {

            resultData.title = '上班'
          } else {

            if (res.data.data[i].cross == 1) {
              resultData.title = '下班' + '\t次日'
            } else {
              resultData.title = '下班'
            }
          }
          var locationData = {}
          if (res.data.data[i].position_info != undefined && res.data.data[i].position_info != null && res.data.data[i].position_info.length != 0) {
            resultData.hasLocation = true
            locationData.addr_name = res.data.data[i].position_info.name
            locationData.addr = res.data.data[i].position_info.address
            var locations = res.data.data[i].position_info.coordinate.split(',')
            locationData.lat = locations[1]
            locationData.lng = locations[0]
            resultData.locationData = locationData
          } else {
            resultData.hasLocation = false
            resultData.form_data = []
          }
          resultList.push(resultData)
        }

        this.setData({
          attendanceList: resultList
        })

      },
      (err) => {

      }
    )
  }
  ,
  getDayStatus: function (date, task_id) {
    var rDate = {
      team_id: team_id,
      project_id: project_id,
      date: date,
      task_id: task_id
    }

    dmNetwork.get(dmNetwork.attdanceDetail, rDate, (res) => {

      extra_info = res.data.data.extra_info
      for (var i = 0; i < res.data.data.attendance_list.length; i++) {
        res.data.data.attendance_list[i].task_id = task_id
        res.data.data.attendance_list[i].isShowNextDay = false

        if (res.data.data.attendance_list[i].attend_nextday == 1) {
          res.data.data.attendance_list[i].isShowNextDay = true
        }
      
        if (res.data.data.attendance_list[i].action_log instanceof Array) {
          res.data.data.attendance_list[i].hasAction = false
        } else {
          var statuStr = ''
          var aLog = res.data.data.attendance_list[i].action_log;
        
          for (var j = 0; j < aLog.status.length; j++) {
            statuStr += aLog.status[j].name
          }
          res.data.data.attendance_list[i].hasAction = true
          res.data.data.attendance_list[i].actionText = util.formatTime(new Date(aLog.action_time * 1000)) + aLog.admin_name + '将' + statuStr + '改为正常'
        }
       
        if (i % 2 == 0) {
          res.data.data.attendance_list[i].title = '上班'
        } else {

          if (res.data.data.attendance_list[i].cross == 1) {
            res.data.data.attendance_list[i].title = '下班' + '\t次日'
          } else {
            res.data.data.attendance_list[i].title = '下班'
          }
        }
        
        if (!(res.data.data.attendance_list[i].abnormal_reason == '')) {
          res.data.data.attendance_list[i].hasReason = false
        } else {
          res.data.data.attendance_list[i].hasReason = true
        }
        var formData = res.data.data.attendance_list[i].form_data
        res.data.data.attendance_list[i].hasLocation = false
        res.data.data.attendance_list[i].hasImage = false
        for (var j = 0; j < formData.length; j++) {
          if (formData[j].type == "Location") {
            res.data.data.attendance_list[i].hasLocation = true;
            res.data.data.attendance_list[i].locationData = formData[j].value
          }
          if (formData[j].type == "Imageview" && res.data.data.attendance_list[i].hasImage == false) {
            if (formData[j].value.thumb_url.length!=0){
              res.data.data.attendance_list[i].hasImage = true
            }else{
              continue
            }
            res.data.data.attendance_list[i].images = []
            var len = 3;
            if (formData[j].value.thumb_url.length > 3) {
              len = 3
            } else {
              len = formData[j].value.thumb_url.length;
            }



            for (var k = 0; k < len; k++) {
              res.data.data.attendance_list[i].images.push(formData[j].value.url[k])
            }
          }
        }
      }

      this.setData({
        attendanceList: res.data.data.attendance_list
      })
    }, (error) => {

    })
  },
  handleCalendar(e) {
    const handle = e.currentTarget.dataset.handle;  //得到 data-handle 值
    const cur_year = this.data.cur_year;
    const cur_month = this.data.cur_month;
    if (handle === 'prev') {
      let newMonth = cur_month - 1;
      let newYear = cur_year;
      if (newMonth < 1) {
        newYear = cur_year - 1;
        newMonth = 12;
      }

      this.calculateDays(newYear, newMonth); //重新计算天数
      this.calculateEmptyGrids(newYear, newMonth); //重新计算空格

      this.setData({
        cur_year: newYear,
        cur_month: newMonth
      })
      this.getMonthStatus(newYear + '-' + newMonth)

    } else {
      let newMonth = cur_month + 1;
      let newYear = cur_year;
      if (newMonth > 12) {
        newYear = cur_year + 1;
        newMonth = 1;
      }

      this.calculateDays(newYear, newMonth);
      this.calculateEmptyGrids(newYear, newMonth);

      this.setData({
        cur_year: newYear,
        cur_month: newMonth
      })
      this.getMonthStatus(newYear + '-' + newMonth)
    }
  },
  clickLocation: function (e) {
    const lData = e.currentTarget.dataset.location;
    const idx = e.currentTarget.dataset.idx;

    var date = this.data.cur_year + '-' + this.data.cur_month + '-' + this.data.cur_date
    var atten = this.data.attendanceList[idx]

    wx.navigateTo({
      url: '../address/address?team_id=' + team_id + '&project_id=' + project_id + '&attendance_id=' + atten.attendance_id + '&date=' + date + '&task_id=' + atten.task_id + "&lat=" + atten.locationData.lat + "&lng=" + atten.locationData.lng
    })

  },

  clickDetail: function (e) {
    const item = e.currentTarget.dataset.item;
    if (item.form_data == undefined) {
      return
    }

    if (item.form_data.length == 0) {
      return
    }
    wx.setStorage({
      key: 'attendance_detail',
      data: item.form_data,
    })
    wx.navigateTo({
      url: '../../dataform/detail/detail?title=打卡详情&team_id=' + this.data.team_id + '&project_id=' + this.data.project_id + 'with_change=0'
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },


})